package org.tp8.sampleapp.service.impl;

import javax.annotation.Resource;
import javax.jws.WebService;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.jms.JmsException;
import org.springframework.jms.core.JmsTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.tp8.sampleapp.exc.SampleAppException;
import org.tp8.sampleapp.jms.messagecreator.MessageCreatorImpl;
import org.tp8.sampleapp.model.Course;
import org.tp8.sampleapp.model.Teacher;
import org.tp8.sampleapp.service.abs.AbstractService;
import org.tp8.sampleapp.service.intf.JMSService;
import org.tp8.sampleapp.util.SampleAppLogger;

/**
 * The Class StudentServiceImpl.
 */
@Transactional(propagation = Propagation.REQUIRED)
@Service(value = "jmsService")
@WebService(endpointInterface = "org.tp8.sampleapp.service.intf.JMSService")
public class JMSServiceImpl extends AbstractService implements JMSService {

	/**
	 * The Constant log.
	 */
	public final static SampleAppLogger log = new SampleAppLogger(
			JMSServiceImpl.class);

	/**
	 * The app context.
	 */
	@Resource
	private ApplicationContext appContext;

	/**
	 * The jms template.
	 */
	@Autowired
	protected JmsTemplate jmsTemplate;

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.tp8.sampleapp.service.intf.JMSService#send(org.tp8.sampleapp.model
	 * .Teacher)
	 */
	@Override
	public Teacher sendTeacher(Teacher teacher) throws SampleAppException {
		log.debug("Sending JMS : " + teacher);

		@SuppressWarnings("unchecked")
		MessageCreatorImpl<Teacher> messageCreator = appContext
				.getBean(MessageCreatorImpl.class);
		messageCreator.setCurMessage(teacher);
		try {
			jmsTemplate.send(messageCreator);
		} catch (JmsException exc) {
			throw new SampleAppException(exc);
		}
		log.info("Sent JMS message.");

		return teacher;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.tp8.sampleapp.service.intf.JMSService#send(java.lang.String)
	 */
	@Override
	public Course sendCourse(String title) throws SampleAppException {
		Course course = new Course();
		course.setId(-1L);
		course.setTitle(title);
		
		log.debug("Sending JMS : " + course);

		@SuppressWarnings("unchecked")
		MessageCreatorImpl<Course> messageCreator = appContext
				.getBean(MessageCreatorImpl.class);
		messageCreator.setCurMessage(course);
		try {
			jmsTemplate.send("sampleQueueForCamel", messageCreator);
		} catch (JmsException exc) {
			throw new SampleAppException(exc);
		}
		log.info("Sent JMS message.");

		return course;
	}

}
